<template>
	<view class="content">
		<view class="charging-info" v-if="detail">

			<view class="box">
				<text class="section-title">充电信息</text>
				<!-- 充电进度环 -->
				<view class="progress-circle">
					<view class="circle-wrapper">
						
						<circle-progress 
						  v-if="detail.status != -1"
							:progress="detail.soc || 0" 
							:status="statusText[detail.status]"
							:statusProgressColor="statusColor[detail.status]['statusProgressColor']"
							:progressColor="statusColor[detail.status]['progressColor']"
							:progressWidth="160" 
						/>
						<circle-progress v-else :progress="detail.soc || 0" status="结束异常" statusProgressColor="#FC0A01" progressColor="rgba(252, 10, 1, 0.2)" />
					
					</view>
				</view>
				<!-- 时间信息 -->
				<view class="time-info">
					<view class="time-block">
						<text class="date">{{ detail.startDate.date }}</text>
						<text class="time">{{ detail.startDate.time }}</text>
						<view class="time-label">开始时间</view>
					</view>
					<view class="time-dots">
						<view class="time-dot-timeline">{{ detail.chargingDuration | formatMinutes }}</view>
						<view class="time-dot-wrapper">
							<view class="dot" v-for="n in 9" :key="n" :style="{
								fontSize: 20 + (n * 4) + 'rpx',
								backgroundColor: `rgba(170, 170, 170, ${0.1 + (n * 0.08)})`
							}"></view>
						</view>
						<view class="time-dot-status">结束充电, APP远程停止</view>
					</view>
					<view class="time-block">
						<text class="date">{{ detail.status === 3 ? detail.endDate.date : detail.endData.date }}</text>
						<text class="time">{{ detail.status === 3 ? detail.endDate.time : detail.endData.time }}</text>
						<view class="time-label">{{ detail.status === 3 ? '结束时间' : '预计结束时间' }}</view>
					</view>
				</view>
			</view>

			<!-- 价格信息 -->
			<view class="price-info box">
				<view class="mb-10">
					<text class="section-title">价格信息</text>
				</view>
				<view class="price-row">
					<text class="price-title">当前价格</text>
					<text class="price"><text class="price-symbol">¥</text><text class="price-num">{{ detail.totalPrice }}</text>/度</text>
				</view>
			</view>

			<!-- 优惠卷 -->
			<!-- <view class="coupon-info box">
				<view class="coupon-title">优惠卷</view>
				<view class="coupon-status">无可用优惠卷<u-icon name="arrow-right" size="12" color="#777777"></u-icon></view>
			</view> -->

			<!-- 支付信息 -->
			<view class="terminal-info box" v-if="detail.status >= 3">
				<view class="mb-10">
					<text class="section-title">支付信息</text>
				</view>
				<view class="info-row">
					<text>支付金额</text>
					<text class="info-value">¥ {{ detail.payPrice && detail.payPrice > 0 ? detail.payPrice / 100 : (detail.chargedAmount || 0) }}</text>
				</view>
				<view class="info-row" v-if="detail.couponPrice > 0">
					<text>优惠金额</text>
					<text class="info-value">¥ {{ detail.couponPrice / 100}}</text>
				</view>
				<view class="info-row">
					<text>支付时间</text>
					<text class="info-value">{{ detail.payTime | formatTimes }}</text>
				</view>
				<view class="info-row">
					<text>支付方式</text>
					<text class="info-value">{{ detail.payChannelCode || '未知' }}</text>
				</view>
			</view>

			<!-- 终端信息 -->
			<view class="terminal-info box">
				<view class="mb-10">
					<text class="section-title">终端信息</text>
				</view>
				<view class="info-row" v-if="terminalInfo">
					<text>辅助电源</text>
					<text class="info-value">{{ terminalInfo.voltage }}v</text>
				</view>
				<view class="info-row">
					<text>充电站</text>
					<text class="info-value">{{ detail.stationName }}</text>
				</view>
				<view class="info-row">
					<text>终端名称</text>
					<text class="info-value">{{ detail.terminalName }}</text>
				</view>
			</view>

			<!-- 评价信息 -->
			<view class="pingjia-info box" v-if="commentInfo">
				<text class="section-title">评价信息</text>
				<view class="pingjia-row">
					<view class="pingjia-avatar">
						<u-avatar :src="commentInfo.userAvatar" size="50"></u-avatar>
					</view>
					<view class="pingjia-content" style="flex: 2;">
						<view class="pingjia-head">
							<view class="pingjia-name">{{ commentInfo.userName }}</view>
							<view class="pingjia-score">{{ commentInfo.score }}</view>
						</view>
						<view class="pingjia-text">哇哈哈哈</view>
						<view class="pingjia-img"v-if="commentInfo.images.length > 0">
							<image class="pingjia-img-item" v-for="image in commentInfo.images" :src="image" mode="aspectFill"></image>
						</view>
						<view class="pingjia-time">{{ commentInfo.createTime | formatTimes }}</view>
					</view>
				</view>
			</view>

			<!-- 开票信息 -->
			<view class="invoice-info box" v-if="invoiceInfo" @tap="toLink('/pages/order/invoice-detail?id=' + invoiceInfo.id)">
				<view class="invoice-title">
					<text class="section-title">开票信息</text>
					<view class="invoice-status">{{ invoiceInfo.status == 1 ? '开票中' : '已完成' }}</view>
				</view>
				<view class="invoice-row">
					<text>申请时间</text>
					<text class="info-value">{{ invoiceInfo.createTime | formatTimes }}</text>
				</view>
				<view class="invoice-row">
					<text>开票金额</text>
					<text class="info-value">¥ {{ invoiceInfo.amount }}</text>
				</view>
				<view class="invoice-row">
					<text>开票内容</text>
					<text class="info-value">{{ invoiceInfo.invoiceContent }}</text>
				</view>
				<view class="invoice-row">
					<text>发票类型</text>
					<text class="info-value">{{ invoiceInfo.invoiceType }}</text>
				</view>
			</view>
		</view>

		<!-- 底部固定按钮 -->
		<view class="fixed-bottom" v-if="detail && (detail.status === 0 || detail.status === 2 || detail.status === 3)">
			<!-- 结束充电按钮 -->
			<view class="end-charging" @tap="handleStopCharging(detail)" v-if="detail.status === 0">
				结束充电
			</view>

			<!-- 立即支付按钮 -->
			<view class="end-charging" @tap="handlePay(detail)" v-if="detail.status === 2">
				立即支付
			</view>

			<!-- 申请开票和评价按钮-->
			<view class="btn-row" v-if="detail.status === 3">
				<view class="btn apply-invoice" @tap="toLink('/pages/user/users/invoice/apply?id=' + id)">申请开票</view>
				<view class="btn pingjia" :class="{disabled: detail.commented == 1}" @tap="toCommentPage">
					{{ detail.commented == 1 ? '已评价' : '评价' }}
				</view>
			</view>
		</view>
		
		<!-- 优惠券选择器组件 -->
		<coupon-selector 
			ref="couponSelector"
			:orderAmount="currentOrderAmount"
			:coupons="availableCoupons"
			@select="onCouponSelect"
		/>
		
		<!-- 支付组件 -->
		<payment 
			v-if="currentOrder && currentOrder.id"
			:show="showPayment"
			:amount="currentOrderAmount"
			:orderId="currentOrder.id"
			:payOrderId="currentOrder.id"
			@payment-success="onPaymentSuccess"
			@payment-error="onPaymentFail"
			@close="showPayment = false"
		/>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import CircleProgress from '@/components/circle-progress/circle-progress.vue'
	import { formatMinutes, formatTimestamp } from '@/utils/index.js';
	import Payment from '@/components/payment/payment.vue'
	import CouponSelector from '@/components/coupon-selector'
	
	export default {
		components: {
			CircleProgress,
			Payment,
			CouponSelector
		},
		data() {
			return {
				timeData: {},
				detail: null,
				timestamp: 0,
				show1: true,
				show2: false,
				id: 0,
				terminalInfo: null, // 终端信息
				commentInfo: null, // 评论信息
				invoiceInfo: null, // 发票信息
				currentOrder: null,
				currentOrderAmount: 0,
				selectedCoupon: null,
				availableCoupons: [],
				// 添加状态文本和颜色配置
				statusText: ['进行中', '结算中', '待支付', '已支付', '已开票', '开票中'],
				statusColor: [
					{ statusProgressColor: '#FF4600', progressColor: '#FFE4DB',  statusTextColor: '#1C6EFB', statusBackgroundColor: '#E7F2FF' },
					{ statusProgressColor: '#FF9900', progressColor: 'rgba(255, 153, 0, 0.3)',  statusTextColor: '#FF9900', statusBackgroundColor: '#FFF4E6' },
					{ statusProgressColor: '#FF4600', progressColor: '#FFE4DB',  statusTextColor: '#FF4600', statusBackgroundColor: '#FFE4DB' },
					{ statusProgressColor: '#42E0A2', progressColor: 'rgba(66, 224, 162, 0.3)',  statusTextColor: '#42E0A2', statusBackgroundColor: '#E6FFF5' },
					{ statusProgressColor: '#42e0a2', progressColor: 'rgba(66, 224, 162, 0.3)',  statusTextColor: '#42E0A2', statusBackgroundColor: '#E6FFF5' },
					{ statusProgressColor: '#FF9900', progressColor: 'rgba(255, 153, 0, 0.3)',  statusTextColor: '#FF9900', statusBackgroundColor: '#FFF4E6' },
				],
				showPayment: false,
			}
		},
		computed: {
			//引入store全局变量
			...mapState(['loginState', 'userInfo'])
		},
		onLoad({ id }) {
			this.id = id;
		},
		onShow() {
			this.getdetail();
		},
		methods: {
			toLink(url) {
				uni.navigateTo({ url: url })
			},
			toCommentPage() {
				if (this.detail.commented == 1) return;
				this.toLink('/pages/order/order-pingjia?id=' + this.detail.stationId + '&orderId=' + this.id)
			},
			onChange(e) {
				this.timeData = e
			},
			getdetail() {
				this.$http_api.orderDetail({ id: this.id }).then((res) => {
					res.startDate = formatTimestamp(res.createTime || 0)
					// 根据状态决定结束时间显示
					if (res.status === 3 && res.payTime) {
					    // 状态为3时使用payTime作为结束时间
					    res.endDate = formatTimestamp(res.payTime)
					} else {
					    // 其他状态使用estimatedTime
					    res.endData = formatTimestamp(res.estimatedTime || 0)
					}
					this.detail = res
					// this.getTerminalInfo(res.terminalId);
					this.getOrderInvoiceInfo(res.id);
					this.getOrderComment(res.stationId);
				})
			},
			// 获取终端信息
			getTerminalInfo(terminalId) {
				this.$http_api.chargingStationInfo({ id: terminalId }).then(res => {
					this.terminalInfo = res;
				});
			},
			// 获取订单开票信息
			getOrderInvoiceInfo(orderId) {
				this.$http_api.orderInvoiceDetail({ id: orderId }).then(res => {
					this.invoiceInfo = res;
				})
			},
			// 获取订单评论
			getOrderComment(id) {
				this.$http_api.orderComment({ id }).then(res => {
					this.commentInfo = res;
				})
			},
			//结束订单
			endcd() {

			},
			gtobak() {
				uni.switchTab({
					url: '/pages/user/user'
				})
			},
			handlePay(order) {
				this.currentOrder = order
				this.currentOrderAmount = order.chargedAmount
				this.showPayment = true
			},
			handleStopCharging(order) {
				// 先弹出确认框
				uni.showModal({
					title: '确认结束充电',
					content: '是否确认结束当前充电?',
					success: (res) => {
						if (res.confirm) {
							// 用户点击确定后继续原有逻辑
							this.currentOrder = order
							this.currentOrderAmount = order.chargedAmount * 100
							
							// 检查是否有可用优惠券
							this.$http_api.couponList({ status: 1, pageNo: 1, pageSize: 100 }).then(res => {
								this.availableCoupons = (res.list || []).filter(coupon => {
									return parseFloat(this.currentOrderAmount) >= parseFloat(coupon.usePrice)
								})
								if (this.availableCoupons.length > 0) {
									this.$refs.couponSelector.show()
								} else {
									this.confirmStopCharging()
								}
							}).catch(err => {
								this.confirmStopCharging()
							})
						}
					}
				})
			},
			// 优惠券选择回调
			onCouponSelect(coupon) {
				this.selectedCoupon = coupon
				this.confirmStopCharging()
			},
			// 确认结束充电
			confirmStopCharging() {
				const params = {
					orderId: this.currentOrder.id,
					couponId: this.selectedCoupon?.id ? [this.selectedCoupon?.id] : []
				}
				this.$http_api.finishOrder(params).then(res => {
					uni.$u.toast('结束充电成功')
					this.getdetail()
				}).finally(() => {
					this.selectedCoupon = null
					this.currentOrder = null
				})
			},
			// Add payment callback methods
			onPaymentSuccess() {
				this.showPayment = false
				uni.$u.toast('支付成功')
				this.getdetail()
			},
			
			onPaymentFail() {
				uni.$u.toast('支付失败')
			},
		},
		filters: {
			formatMinutes(minute) {
				return formatMinutes(minute)
			},
			formatTimes(time) {
				if (!time) return '无';
				const data = formatTimestamp(time);
				return data.date + ' ' + data.time
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 20rpx;
		padding-bottom: 180rpx; // 增加底部padding,为固定按钮留出空间
		font-family: "PINGFANG";
	}

	.box {
		background-color: #fff;
		border-radius: 30rpx;
		padding: 30rpx 30rpx;
	}

	.section-title {
		font-size: 34rpx;
		font-weight: bold;
		margin: 30rpx 0;
		padding-bottom: 20rpx;
	}

	.progress-circle {
		display: flex;
		justify-content: center;
		padding: 40rpx 0;

		.circle-wrapper {
			position: relative;
		}
	}

	.time-info {
		display: flex;
		justify-content: space-between;
		margin: 30rpx 0 0 0;

		.time-dots {
			.time-dot-timeline {
				font-size: 24rpx;
				color: #42E0A2;
				text-align: center;
				font-weight: bold;
				height: 30rpx;
				//margin: 30rpx 0;
			}

			.time-dot-wrapper {
				display: flex;
				margin-top: 35rpx;

				.dot {
					width: 10rpx;
					height: 10rpx;
					margin: 0 8rpx;
					background-color: #AAAAAA;
					border-radius: 50%;
				}
			}

			.time-dot-status {
				font-size: 18rpx;
				color: #777777;
				text-align: center;
				margin-top: 35rpx;
			}


		}

		.time-block {
			text-align: center;

			.date,
			.time {
				display: block;
				margin-bottom: 10rpx;
				color: #333;
			}

			.date {
				font-size: 26rpx;
				color: #AAAAAA;
			}

			.time {
				font-weight: bold;
				font-size: 36rpx;
			}

			.time-label {
				display: inline-block;
				padding: 10rpx 30rpx;
				border-radius: 20rpx;
				background: #42E0A2;
				color: #fff;
				font-size: 24rpx;
			}
		}
	}

	.coupon-info {
		display: flex;
		height: 131rpx;
		justify-content: space-between;
		align-items: center;
		padding: 1rpx 30rpx !important;

		.coupon-title {
			font-size: 30.56rpx;
			font-weight: bold;
		}

		.coupon-status {
			font-size: 25rpx;
			color: #777777;
			display: flex;
		}
	}

	.price-info,
	.terminal-info,
	.invoice-info,
	.pingjia-info {
		margin: 30rpx 0;

		.pingjia-row {
			display: flex;
			margin-top: 30rpx;

			.pingjia-content {
				margin-left: 30rpx;

				.pingjia-head {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 10rpx;
					width: calc(100% - 40rpx);

					.pingjia-name {
						font-weight: 400;
						font-size: 32rpx;
						color: #333;
					}

					.pingjia-score {
						font-size: 40rpx;
						color: #FC0A01;
					}
				}

				.pingjia-text {
					font-size: 24rpx;
					color: #333;
					width: calc(100% - 10rpx);
					margin: 20rpx 0;
				}

				.pingjia-img {
					display: flex;
					flex-wrap: wrap;
					width: calc(100% - 10rpx);

					.pingjia-img-item {
						width: 100rpx;
						height: 100rpx;
						margin: 10rpx;

						&:nth-child(5n) {
							margin-right: 0;
						}
					}
				}

				.pingjia-time {
					font-size: 24rpx;
					color: #AAAAAA;
					text-align: left;
				}
			}
		}

		.invoice-title {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.section-title {
				margin: 0;
			}

			.invoice-status {
				font-size: 24rpx;
				color: #FF4600;
			}
		}

		.price-row,
		.info-row,
		.invoice-row {
			display: flex;
			justify-content: space-between;
			padding: 6rpx 0;
			//border-bottom: 1rpx solid #eee;
			font-size: 28rpx;

			.price-title {
				margin-top: 15rpx;
			}

			.info-value {
				color: #777777;
			}

			.price {
				.price-symbol {
					font-size: 35rpx;
					color: #ff4d4f;
					margin: 0 10rpx;
				}

				.price-num {
					font-weight: bold;
					color: #ff4d4f;
					font-size: 50rpx;
				}
			}
		}
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 40rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 99;

		.end-charging {
			width: 100%;
			text-align: center;
			background: #42E0A2;
			color: #fff;
			padding: 25rpx 0;
			border-radius: 50rpx;
			font-size: 28rpx;
		}

		.btn-row {
			display: flex;
			justify-content: space-between;

			.btn {
				width: 48%;
				background: #42E0A2;
				color: #fff;
				text-align: center;
				padding: 25rpx 0;
				border-radius: 50rpx;
				font-size: 28rpx;

				&.pingjia {
					background-color: #1C6EFB;
				}
				
				&.disabled {
					background: #ccc;
					opacity: 0.7;
				}
			}
		}
	}
	
	.mb-10 {
		margin-bottom: 20rpx;
	}
</style>